import {
  message,
} from 'antd';
// 处理 页面型时使用
import {estateList,addEstate,remove,estateDetail,editEstate,updateFile,deleteFile} from "@/services/estate"
import {searchList} from "@/services/city"
import {markCascadeList} from '@/utils/utils'

async function getFileList(api_list) {
    const list = [];
    for (let i =0; i<api_list.length; i++){
      const fileApi = api_list[i];

      const file_name = fileApi.split("/")[fileApi.split("/").length-1];
      const file_id = file_name.substring(0,file_name.lastIndexOf("."));
      const suffix = file_name.substring(file_name.lastIndexOf('.')+1);
      let thumbUrl ;
      if (suffix === 'mp4'){
        thumbUrl = await getVideoBase64(fileApi);
      }
      list.push({
        uid: file_id,
        name: file_name,
        status: 'done',
        url: fileApi,
        thumbUrl:thumbUrl
      })
    }
    return list;
}



const  getVideoBase64 = async (url)=> {
  return new Promise(function (resolve, reject) {
    let dataURL = '';
    let video = document.createElement("video");
    video.setAttribute('crossOrigin', 'anonymous');//处理跨域
    video.setAttribute('src', url);
    video.setAttribute('width', 400);
    video.setAttribute('height', 240);
    video.currentTime =1;
    video.addEventListener('loadeddata', function () {
      let canvas = document.createElement("canvas"),
        width = video.width, //canvas的尺寸和图片一样
        height = video.height;
      canvas.width = width;
      canvas.height = height;
      canvas.getContext("2d").drawImage(video, 0, 0, width, height); //绘制canvas
      dataURL = canvas.toDataURL('image/jpeg'); //转换为base64
      //document.body.removeChild(video);
      resolve(dataURL);
    });
  })
}
export default {
  namespace: 'estate',
  state: {
      type_list  : [
        {
          name :'周边',
          value :'around'
        },
        {
          name :'国外',
          value :'foreign'
        },
        {
          name :'国内',
          value :'inside'
        },
      ],
    itemImgFile :[],
    contentImgFile :[],
    carouselImageFile :[],
    carouselVideoFile :[],
  },
  effects: {
    * fetch({payload}, {call, put}) {
      const list = yield call(estateList, payload);
      console.log(list);
      yield put({
        type: 'save',
        payload: {
          list: list.list,
          pagination: {
            page_size: list.page_size,
            total_pages: list.total_pages,total: list.total_elements,
            page_num: list.page_num,current:list.page_num,
          }
        },
      });
    },
    * searchList({payload}, {call, put}) {
      const list = yield call(estateList, payload);
      console.log(list);
      yield put({
        type: 'save',
        payload: {
          list: list.list,
          pagination: {
            page_size: list.page_size,
            total_pages: list.total_pages,total: list.total_elements,
            page_num: list.page_num,current:list.page_num,
          }
        },
      });
    },
    *createEstate({payload}, {call, put}) {
      console.log(payload);
      const response = yield call(addEstate, payload);
      if (response && response.return_code === 'SUCCESS') return true
    },
    *deleteById({payload}, {call, put}) {
      const response = yield call(remove, payload);
      if (response && response.return_code === 'SUCCESS') return true
    },
    * showCreateModal({payload}, {call, put}) {
      const cityResponse = yield  call(searchList);
      const area_cascade_list = cityResponse && cityResponse.return_code === 'SUCCESS' ? markCascadeList({lable_name:'name',value_name:'id',children_name:'children'},cityResponse.data):[];
      yield put({
        type: 'save',
        payload: {
          createModalVisible :true,
          city_list:area_cascade_list
        },
      });
    },
    * showUpdateModal ({payload}, {call, put}) {
      const cityResponse = yield  call(searchList);
      const detailResponse = yield call(estateDetail,payload);
      const area_cascade_list = cityResponse && cityResponse.return_code === 'SUCCESS' ? markCascadeList({lable_name:'name',value_name:'id',children_name:'children'},cityResponse.data):[];
      console.log(detailResponse);
      yield put({
        type: 'save',
        payload: {
          updateModalVisible :true,
          city_list:area_cascade_list,
          updateData : detailResponse && detailResponse.return_code === 'SUCCESS'? detailResponse.data :{}
        },
      });
    },
    * showFileModal ({payload}, {call, put}) {
      const detailResponse = yield call(estateDetail,payload);
      if (detailResponse && detailResponse.return_code === 'SUCCESS'){
        const updateData =detailResponse.data;

        let itemImgFile =[];
        let contentImgFile  = [];
        let carouselImageFile =[];
        let carouselVideoFile =[];

        if (updateData && updateData.item_image){
          itemImgFile = yield getFileList([updateData.item_image]);
        }

        if (updateData && updateData.content_image){
          let content_img_list = updateData.content_image.split(",");
          contentImgFile = yield getFileList(content_img_list);
        }

        if (updateData && updateData.carousel_image_list){
          updateData.carousel_image_list.map((item)=>{
            if (item.type ==='image'){
              carouselImageFile.push(item.image_content)
            }
            if (item.type ==='video'){
              carouselVideoFile.push(item.play_url)
            }
          });
          console.log("===2131234",carouselImageFile);
          console.log("===2131234",carouselVideoFile);
          carouselImageFile = yield getFileList(carouselImageFile);
          carouselVideoFile = yield getFileList(carouselVideoFile);
        }

        console.log("===========4",carouselImageFile);
        console.log("===========4",carouselVideoFile);
        yield put({
          type: 'save',
          payload: {
            fileModalVisible :true,
            updateData : detailResponse && detailResponse.return_code === 'SUCCESS'? detailResponse.data :{},
            itemImgFile:itemImgFile,
            contentImgFile:contentImgFile,
            carouselImageFile:carouselImageFile,
            carouselVideoFile:carouselVideoFile,
          },
        });

      }




    },
    *updateEstate  ({payload}, {call, put}) {
      const response = yield call(editEstate,payload);
      if (response && response.return_code === 'SUCCESS') return true
    },
    *delEstateFile ({payload}, {call, put}) {
      const response = yield call(deleteFile,payload);
      if (response && response.return_code === 'SUCCESS') return true
    },
    *updateEstateFile  ({payload}, {call, put}) {
      const response = yield call(updateFile,payload);
      if (response && response.return_code === 'SUCCESS') return true
    },
  },
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  }
}